var Shop = function(){
	this.shopInfo = {};
	var shopContainer = false;
    var this_ = this;
    var shop = false;
    //Тип запроса по которому будем получать данные из mlhAPI надо менять на get_rc если мы что то поменяли
    var getDataMode = 'get';
    this.init = function(){
        url = app.cloneArray(url || app.currentUrl);
        if(this[url[1]])this[url[1]]();
        else this.list();
    }
    this.list = function(){
    	if(app.user_info.user_logined!=true){
            console.log('Только для зарегистрированных');
            app.static.registered_only();
            return;
        }
        app.topMenu.breadcrumbList[1] = ['Список магазинов','/shop/list'];
        app.topMenu.breadcrumbList[2] = false;
        app.topMenu.buildBreadcrumb();
        app.leftMenu.setProfileLeftMenu();
        //загружаем шаблон
		var el = $.tmpl('manage_shop_list', 
		{
			show_select: app.user_info.user_shop.length > 1
		});
		shopContainer = $(el).find('[rel=shop_list]:first');
		if(!app.user_info.user_shop.length)shopContainer.html('');
		el.prependTo(app.elements.general_content.html(''));
        var erase=true;
        for(var k in app.user_info.user_shop){
			mlhAPI.get({
	            c: 'shop',
	            v: 'showByUser',
                requestType: getDataMode,
	            name: app.user_info.user_shop[k].name
	        },function(data){
	            if(erase){
	               app.main.unmask();
                   shopContainer.html('');
                   erase = false;
                }
	            if(data.result=='error'){
	            	return;
	            }
	            data.data.info['tags_count'] = data.data.info.tags.length;
	            this_.shopInfo[data.data.info.name]=data.data.info;
                data.data.info['edit'] = true;
				var el = $.tmpl('manage_shop_element', data.data.info);
				el.find('.tags .koma:last').hide();
				el.appendTo(shopContainer);
				app.decorate.setEvents(el);
	        });
        }
        getDataMode = 'get';
    }
    this.edit = function(){
        if(app.user_info.user_logined!=true){
            console.log('Только для зарегистрированных');
            app.static.registered_only();
            return;
        }
        shop = app.currentUrl[2] ? app.currentUrl[2] : false;
        
        var build = function(data){
            jQuery.extend(data, {
	            editMode: shop!=false
	        });
            var el = $.tmpl('edit_shop',data);
            el.prependTo(app.elements.general_content.html(''));
            app.decorate.validateRule($('#shopEditForm input, #shopEditForm textarea, #shopEditForm select'),
            {
                rules:{
                    name: function(value,controlGroup){
                            if (!value.match(/^[a-z0-9_]+$/gi)){
                                return 'Допускаются только символы латиницы, цифры и _';
                            }else{
                                mlhAPI.get({
                                    c: 'shop',
                                    v: 'checkShopName',
                                    name: value
                                },function(data){
                                    console.log(data);
                                    if(data.data.result=='error'){
                                        controlGroup.find('.alert:first').text(data.data.errors['name']).show();
                                        controlGroup.attr('class','row control-group error');
                                    }
                                });
                            }
                            return false;
                        }
                },
                endValid: function(error){
                    if(!error){
                        $('#shopEditForm .control-group').each(function(){
                            if($(this).hasClass('error')) error = true;
                            $(this).find('*[rel=req]').each(function(){
                                var value = this.tagName=='textarea' ? $(this).text() : $(this).attr('value');
                                if(!value) error = true;
                            });
                        });
                    }
                    $('#shopEditForm button[type=submit]').attr('class', !error ? 'btn btn-success' : 'btn btn-warning');
                    if(!error){
                       $('#shopEditForm').find('.alert-info').show();
                       $('#shopEditForm').find('.alert[data-type=error]').hide();
                    }
                }
            });
            var newImage = false;
            app.decorate.imageForm($('#shopEditForm'), data.image, newImage);
            $('#shopEditForm form').submit(function(){
                if($('#shopEditForm button[type=submit]').hasClass('btn-warning')){
                    $('#shopEditForm').find('.alert[data-type=error]').addClass('alert-error').text("Заполните все поля формы").show();
                    $('#shopEditForm').find('.alert-info').hide();
                    $('#shopEditForm').find('*[rel=req]').each(function(){
                        var value = $(this).val();
                        if(this.tagName=='SELECT' && (value==0 || value == '0') )value = false;
                        if(!value) {
                        	$(this).parents('.control-group:first')
                        		.attr('class','row control-group warning span12 no_left_margin')
                        		.find('.alert:first').text('Это поле обязательно надо заполнить').show();
                        	
                        }
                    });
                    return false;
                }
                var formData = {}
                var sData = $(this).serializeArray();
                for(var i = 0; i < sData.length; i++) {
                    formData[sData[i].name] = sData[i].value;
                }
                formData['c'] = 'shop';
                formData['v'] = shop ? 'save' : 'register';
                formData['requestType'] = 'post';
                formData['tag_id'] = $('#shopEditForm [name=tags]').getAsJSON();
                formData['newImage'] = newImage ? 1 : 0;
                if(shop) formData['shop_id'] = data['shop_id'];
                console.log(formData);
                //return false;
                mlhAPI.post(formData,function(data){
                    console.log(data);
                    if(data.data.result=='error'){
                        var text = "";
                        for(var k in data.data.errors){
                            if(k=='email')$('#shopEditForm input[name=email]').parents('.control-group:first').attr('class','row control-group error');
                            text += "<div>" + data.data.errors[k] +"</div>";
                        }
                        $('#shopEditForm').find('.alert[data-type=error]').addClass('alert-error').html(text).show();
                        $('#shopEditForm').find('.alert-info').hide();
                        $('#shopEditForm button[type=submit]').attr('class', 'btn btn-warning');
                    }else{
                        $('#shopEditForm').find('.alert[data-type=error]').hide();
                        //$('#shopEditForm').find('.alert-info').html(shop ? 'Вы успешно отредактировали магазин' : 'Вы успешно создали магазин').show();
                        app.static.success({description:(shop ? 'Вы успешно отредактировали магазин' : 'Вы успешно создали магазин')})
                        $('#shopEditForm button[type=submit]').attr('class', 'btn btn-success');
                        //setTimeout(function(){app.go('#shop/list')},2000);
                        getDataMode = 'get_rc';
                        app.go('#shop/list');
                    }
                });
                return false;
            });
           mlhAPI.category.getList({
               model:'shop',
               callback: function(list){
                    console.log("Category List", list);
                    if(list.result=='error'){
                        return;
                    }
                    delete list.data['log'];
                    var select = $('#shopEditForm select[name=category_id]');
                    app.decorate.buildSelectIttems($('#shopEditForm select[name=category_id]'), {
                        list: list.data,
                        key: 'category_id',
                        active: data['category_id'],
                        multilevelKey: 'child'
                    });
                }
           });
           mlhAPI.currency.getList({
               callback: function(list){
                    console.log("Curency List", list);
                    if(list.result=='error'){
                        return;
                    }
                    app.decorate.buildSelectIttems($('#shopEditForm select[name=currency_id]'), {
                        list: list.data.list,
                        key: 'currency_id',
                        title: function(data){
                        	return data.name + " - " + data.title;
                        },
                        active: data['currency_id']
                    });
                }
           });
           mlhAPI.main.getTemplateList({
               callback: function(list){
                    console.log("Template List", list);
                    if(list.result=='error'){
                        return;
                    }
                    app.decorate.buildSelectIttems($('#shopEditForm select[name=template_id]'), {
                        list: list.data.list,
                        key: 'template_id',
                        active: data['template_id']
                    });

                }
           });
           setTimeout(function(){
                $('#shopEditForm [name=tags]').tagsInput(
                {
                    width:'auto',
                    defaultText: '+ добавить',
                    autocomplete_url:'http://'+location.host+'/api.php?h=tag&v=autocomplete'
                });
           },300);
    	}  
    	if(!shop){
            build({});
            app.main.unmask();
        }else{
            mlhAPI.get({
	            c: 'shop',
	            v: 'showByUser',
	            name: shop
	        },function(data){
	            console.log("Shop data", data);
                app.main.unmask();
	            if(data.result=='error'){
	            	return;
	            }
	            data.data.info['tags_count'] = data.data.info.tags.length;
	            build(data.data.info);
	        });
            app.topMenu.breadcrumbList[1] = ['Список магазинов','/shop/list'];
            app.topMenu.breadcrumbList[2] = [shop,'/shop/edit/' + shop];
            app.topMenu.buildBreadcrumb();
        }
        if(shop){
            $('#shopEditForm button[type=submit]').text('Редактировать магазин');
        }
        //показываем левое меню
        app.leftMenu.setEditShopLeftMenu(shop);    
    }
}

app['shop'] = new Shop();